package cn.sh.library.gmwx.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.sh.library.gmwx.bean.InstanceSearchBean;
import cn.sh.library.gmwx.bean.WorkSearchBean;
import cn.sh.library.gmwx.dto.Pager;
import cn.sh.library.gmwx.dto.QueryResult;
import cn.sh.library.gmwx.service.BookService;
import cn.sh.library.gmwx.sparql.InstanceSparql;
import cn.sh.library.gmwx.sparql.ItemSparql;
import cn.sh.library.gmwx.sparql.WorkSparql;
import cn.sh.library.gmwx.utils.HttpsUtils;
import cn.sh.library.gmwx.utils.JSONUtils;
import net.sf.json.JSONObject;


@Service
public class BookServiceImpl implements BookService {
    @Resource
    private WorkSparql workSparql;
    @Resource
    private InstanceSparql instanceSparql;
    @Resource
    private ItemSparql itemSparql;

    @Override
    public List<Map<String, String>> list(WorkSearchBean search, Pager pager) {
        // String order = "ORDER BY " + pager.getDir() + "(?" + pager.getSort() + ")";
    	String order = "";
    	
        QueryResult<Map<String, String>> queryResult = this.workSparql.searchWorks(search, order, pager);

        pager.calcPageCount(queryResult.getTotalrecord());
        pager.setRowCount(queryResult.getTotalrecord());
        return queryResult.getResultList();
    }

    @Override
    public List<Map<String, String>> instances(InstanceSearchBean search, Pager pager) {
        String order = "ORDER BY DESC(?year)";

        QueryResult<Map<String, String>> queryResult = this.instanceSparql.getWorkInstances(search, order, pager);

        pager.calcPageCount(queryResult.getTotalrecord());
        pager.setRowCount(queryResult.getTotalrecord());
        return queryResult.getResultList();
    }


	@Override
    public String coverByInstance(String uri) {
    	try {
        	List<Map<String, String>> identifiers = itemSparql.getIdentifier(uri);
        	if(identifiers.size() == 0) {
        		return "";
        	}
        	
        	String idString = identifiers.get(0).get("identifier");
			String res = HttpsUtils.doGet("https://fullimg.library.sh.cn/manifests/gmwx/" + idString + ".json");
			Map<String, Object> map = new ObjectMapper().readValue(res, new TypeReference<Map<String,Object>>(){});
			List canvases = (List)((Map<String, Object>)((List)map.get("sequences")).get(0)).get("canvases");
			
			Map<String, String> services = (Map<String, String>) ((Map)((Map)((List)((Map<String, Object>)canvases.get(0)).get("images")).get(0)).get("resource")).get("service");
			return services.get("@id").replace("http://", "https://") + "/full/500,/0/default.jpg";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	return "";
    }
}
